import express, { Application } from 'express';
import cors from 'cors';
import projectRoutes from './routes/projectRoutes';
import timelineRoutes from './routes/timelineRoutes';
import renderRoutes from './routes/renderRoutes';
import assetRoutes from './routes/assetRoutes';
import multer from 'multer';

/**
 * API Server
 * 
 * Main entry point for the API server.
 */

class ApiServer {
  private app: Application;
  private port: number;

  constructor(port: number = 3000) {
    this.app = express();
    this.port = port;
    this.initializeMiddleware();
    this.initializeRoutes();
  }

  /**
   * Initializes middleware
   */
  private initializeMiddleware(): void {
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));
    this.app.use(cors());
    
    // Configure multer for file upload handling
    const upload = multer({ storage: multer.memoryStorage() });
    // Make the upload middleware available to routes
    this.app.use((req, res, next) => {
      // Add multer upload middleware to the request object
      (req as any).upload = upload;
      next();
    });
  }

  /**
   * Initializes routes
   */
  private initializeRoutes(): void {
    // Health check endpoint
    this.app.get('/health', (req, res) => {
      res.json({
        status: 'OK',
        timestamp: new Date().toISOString(),
        service: 'Teaching Animation API'
      });
    });

    // API routes
    this.app.use('/api/projects', projectRoutes);
    this.app.use('/api/timelines', timelineRoutes);
    this.app.use('/api/render', renderRoutes);
    this.app.use('/api/assets', assetRoutes);

    // 404 handler
    this.app.use((req, res) => {
      res.status(404).json({
        success: false,
        message: 'Route not found'
      });
    });

    // Error handler
    this.app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
      console.error('API Error:', err);
      res.status(500).json({
        success: false,
        message: 'Internal server error'
      });
    });
  }

  /**
   * Starts the server
   */
  public start(): void {
    this.app.listen(this.port, () => {
      console.log(`Teaching Animation API server listening at http://localhost:${this.port}`);
    });
  }

  /**
   * Gets the Express application
   * @returns Application - The Express application
   */
  public getApp(): Application {
    return this.app;
  }
}

// Create and start server if this file is run directly
if (require.main === module) {
  const server = new ApiServer(3000);
  server.start();
}

export default ApiServer;